<?php

namespace app\tour\controller;

use think\Db;
use think\Request;
use app\tour\model\Album as AlbumModel;
use think\Session;

vendor('qiniu/php-sdk/autoload.php');

use Qiniu\Auth;
use Qiniu\Storage\BucketManager; //实例化上传类

class Album extends Common
{

    public function album(){

        if (Request::instance()->isAjax()){

            $field = ['id','img_path','sort','create_time','t_admin_tel','admin_rename'];

            $count = AlbumModel::albumList(array(),array(),0,0,true);

            $pagedata = Request::instance()->get();

            $pagesize = $pagedata['limit'];
            $page = (int)$pagedata['page'];
            $startrow = ($page - 1) * $pagesize;

            $data = AlbumModel::albumList($field,array(),$startrow,$pagesize);

            return ['code'=>0,'msg'=>'','count'=>$count,'data'=>$data];

        }else{

            return view();

        }

    }

    public function uploadsImg(){

        $upload =  parent::uploadOneFileToQiniu('lv/tour/album/');

        if ($upload['code'] == 0){

            $addData = [
                'tour_id'     => Session::get('tour_id'),
                'img_path'    => $upload['data'],
                'create_time' => date("Y-m-d H:i:s"),
                't_admin_id'  => Session::get('t_admin_id')
            ];

            $res = AlbumModel::add($addData);

            if ($res !== false){
                return ['code'=>0,'msg'=>'上传成功'];
            }else{
                return ['code'=>1,'msg'=>'上传失败'];
            }

        }else{

            return $upload;

        }


    }

    public function editSort(){

        if (Request::instance()->isAjax()){

            $post = Request::instance()->post();

            $editData = ['sort'=>$post['sort']];

            $res = AlbumModel::editAlbum($post['id'],$editData);

            if ($res !== false){
                return ['code'=>0];
            }else{
                return ['code'=>1];
            }

        }

    }

    public function delImg(){

        if (Request::instance()->isAjax()){
            $post = Request::instance()->post();

            $res = Db::name('tour_img')->where('id',$post['id'])->delete();

            if ($res){

                $accessKey = config("qiniu")["accessKey"];
                $secretKey = config("qiniu")["secretKey"];

                $auth = new Auth($accessKey, $secretKey);
                // 空间
                $bucket = config("qiniu")["bucket"];
                $key_arr = parse_url($post['path']);
                $key = substr($key_arr['path'],1);

                $BucketManager = new BucketManager($auth);

                $res = $BucketManager->delete($bucket,$key);

                return ['code'=>0];

            }else{
                return ['code'=>1];
            }
        }

    }
}